from flask import Flask
import os
import logging
from datetime import datetime, timedelta

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('Inventory_System')

# 导入必要的模块
from flask import Flask, request, g
from flask_jwt_extended import JWTManager, create_access_token, get_jwt_identity, jwt_required

# 创建Flask应用实例
app = Flask(__name__, instance_relative_config=True)

# 修改Jinja2表达式为[[ ... ]]
app.jinja_env.variable_start_string = '[['
app.jinja_env.variable_end_string = ']]'

# JWT配置
app.config['JWT_SECRET_KEY'] = 'your_inventory_jwt_secret_key'
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=24)

# 初始化JWT管理器
jwt = JWTManager(app)

# 导入扩展
from extensions import db, login_manager
from models import User

# 配置数据库
app.config['SECRET_KEY'] = 'inventory_system_secret_key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///inventory.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 初始化扩展
login_manager.init_app(app)
login_manager.login_view = 'auth.login'
db.init_app(app)

# 请求拦截器 - 请求前处理
@app.before_request
def before_request_handler():
    # 记录请求开始时间
    g.start_time = datetime.now()
    
    # 记录请求信息
    logger.info(f"Request: {request.method} {request.path} - IP: {request.remote_addr}")
    
    # 对于API路径，进行JWT验证
    if request.path.startswith('/api/'):
        try:
            from flask_jwt_extended import verify_jwt_in_request, get_jwt, get_jwt_identity
            verify_jwt_in_request()
            current_user_id = get_jwt_identity()
            if current_user_id:
                # 获取用户信息并存储到全局对象
                user = User.query.get(current_user_id)
                if user:
                    g.user_id = current_user_id
                    g.user_role = get_jwt().get('role')
                    g.current_user = user
                    logger.info(f"API用户已登录: {user.username} (ID: {current_user_id}, Role: {g.user_role})")
        except Exception as e:
            logger.warning(f"API JWT验证异常: {str(e)}")
            # 让Flask-JWT-Extended处理JWT验证失败

# 导入蓝图并注册
from routes import main_bp, auth_bp
from routes.product_api import product_api
from routes.supplier_api import supplier_api
from routes.category_api import category_api
from routes.user_api import user_api
from routes.inventory_api import inventory_api
from routes.stock_in_api import stock_in_api
from routes.stock_out_api import stock_out_api
from routes.statistics_api import statistics_api
from routes.upload_api import upload_api

app.register_blueprint(main_bp)
app.register_blueprint(auth_bp, url_prefix='/auth')
app.register_blueprint(product_api)
app.register_blueprint(supplier_api)
app.register_blueprint(category_api)
app.register_blueprint(user_api)
app.register_blueprint(inventory_api)
app.register_blueprint(stock_in_api)
app.register_blueprint(stock_out_api)
app.register_blueprint(statistics_api)
app.register_blueprint(upload_api)

# 添加静态文件路由，用于访问上传的文件
from flask import send_from_directory
import os

@app.route('/files/<path:filename>')
def uploaded_file(filename):
    """提供上传文件的访问"""
    # 将反斜杠转换为正斜杠，确保跨平台兼容性
    filename = filename.replace('\\', '/')
    
    # 构建文件路径
    file_path = os.path.join(app.root_path, 'files', filename)
    
    # 检查文件是否存在
    if not os.path.exists(file_path):
        from flask import abort
        abort(404)
    
    return send_from_directory(os.path.join(app.root_path, 'files'), filename)

# 创建数据库表
with app.app_context():
    from models import User, Supplier, Product, Category, Inventory, StockIn, StockOut
    db.create_all()

if __name__ == '__main__':
    app.run(debug=False)
